package models

import (
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"strconv"
	"wego/utils"
)

type AuthGroup struct {
	Id          int64  `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      int8   `json:"status"`
}

type GroupsQueryparam struct {
	BaseQueryParam
	Status int8
	Sort   string
}

func AuthList(params *GroupsQueryparam) ([]AuthGroup, int64) {
	data := []AuthGroup{}
	query := orm.NewOrm().QueryTable("tp_auth_group")
	if params.Status > 0 {
		query.Filter("status", params.Status)
	}
	if params.Page > 0 && params.Size > 0 {
		query.Limit(params.Size, (params.Page-1)*int64(params.Size))
	}
	sort := "Id"
	if params.Sort != "" {
		sort = params.Sort
	}
	total, _ := query.Count()
	_, _ = query.OrderBy(sort).All(&data)
	return data, total
}

func AuthStatus(m *AuthGroup) error {
	o := orm.NewOrm()
	_, err := o.Update(m, "status")
	return err
}

//删除权限组
func AuthDel(m *AuthGroup) error {
	o := orm.NewOrm()
	err := o.Begin()
	var num int64
	num, err = o.QueryTable("tp_auth_group").Filter("id", m.Id).Delete()

	if num > 0 && err == nil {
		_, err = o.QueryTable("tp_auth_rule").Filter("group_id", m.Id).Delete()
		if err == nil {
			list := []AuthGroupAccess{}
			cond := orm.NewCondition()
			conds := cond.Or(
				"group_id__contains", ","+strconv.Itoa(int(m.Id))+",").Or(
				"group_id__startswith", "["+strconv.Itoa(int(m.Id))+",").Or(
				"group_id__endswith", ","+strconv.Itoa(int(m.Id))+"]").Or(
				"group_id__exact", "["+strconv.Itoa(int(m.Id))+"]")

			_, _ = o.QueryTable("tp_auth_group_access").SetCond(conds).All(&list)
			for _, item := range list {
				var arr []int64
				_ = json.Unmarshal([]byte(item.GroupId), &arr)

				arr = utils.RemoveElement(arr, m.Id)
				str := "["
				for i := 0; i < len(arr); i++ {
					str += strconv.Itoa(int(arr[i]))
				}
				str += "]"
				_, err = o.QueryTable("tp_auth_group_access").Filter("id", item.Id).Update(orm.Params{
					"group_id": str,
				})
				if err != nil {
					err = o.Rollback()
					return err
				}
			}
		}
	}
	if err != nil {
		err = o.Rollback()
	} else {
		err = o.Commit()
	}
	return err
}
